import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { Button, Input, Radio, Modal, message, Tag, Form } from 'antd'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
import menuRoute from 'routes/menuRoute'
import 'styles/financial-management/finance-audit/scan-audit.scss'
import ReconnectingWebSocket from 'reconnectingwebsocket'
import ScanAuditImg from 'images/scan-audit.png'
import financeAuditService from 'containers/financial-management/new-finance-audit/finance-audit.service'
import QuickReply from 'components/template/quick-reply';
import errorMessage from 'share/errorMessage';
import WaterMark from 'components/water-mark';
import { getWsUrl } from 'share/utils';
class ScanAudit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      financeAudit: menuRoute.getRouteItem('finance-audit'),
      connectStatus: false,
      entityList: [],
      rejectEntity: {},
      hasConfirm: false,
      loading: false,
      attachmentOIDs: []
    };
    this.connector = null;
    this.data = [];
  }

  componentWillUnmount = () => {
    if(this.connector)
      this.connector.close();
  };

  handleClickSwitch = () => {
    if(this.connector)
      this.connector.close();
    this.context.router.push(this.state.financeAudit.url.replace(':backType','history'))
  };

  componentDidMount = () => {
    if(this.connector)
      this.connector.close();
    this.openWebSocket();
  };

  openWebSocket = () => {
    let url = getWsUrl('/ws/scancode?scanMode=AUDIT');
    this.connector =  new ReconnectingWebSocket(url);
    this.connector.onopen = this.onOpen;
    this.connector.onerror = this.onError;
    this.connector.onmessage = this.onMessage;
    this.connector.onclose = this.onClose;
  };

  onOpen = () => {
    let body = {
      userOID: this.props.user.userOID,
      token: this.props.authToken.access_token
    };
    let dict = {
      command: 'AUTH',
      body: JSON.stringify(body)
    };
    let dataSend =  JSON.stringify(dict) + '\0';
    this.connector.send(dataSend);
  };

  onError = (error) => {
    this.setState({ connectStatus: false })
  };

  onMessage = (message) => {
    this.data.push(JSON.parse(JSON.stringify(message)).data);
    this.analyseData();
  };

  onClose = () => {
    if(this.state.connectStatus)
      this.setState({connectStatus: false});
  };
  handleFormDetail = (content) => {
    let entityType = content[0] || '';
    let formInfo = entityType ? messages('expense-14.key247')/*单据*/ : '';
    if (+entityType === 5001) {
      formInfo = messages('expense-14.key248')/*发票袋*/;
    }
    let businessCode = content[3] || '';
    formInfo && businessCode && (businessCode = `${formInfo} ${businessCode}`);
    return {
      entityType, businessCode
    }
  };
  analyseData = () => {
    let lastReceive = this.data.pop();
    let end = '\0';
    if (lastReceive.indexOf(end) === -1){
      this.data.push(lastReceive);
      return;
    }
    let temp = lastReceive.split(end);
    let expense = JSON.parse(this.data.join('') + temp[0]);
    if (temp[1] !== ''){
      this.data = [];
      this.data.push(temp[1]);
    }
    if (expense.command === 'ERROR') {
      if(this.state.hasConfirm)
        return ;
      this.setState({ hasConfirm: true });
      Modal.confirm({
        title: 'Oops',
        content: expense.body,
        okText: messages('expense-14.key246')/*重连*/,
        cancelText: messages('expense-14.key249')/*返回普通审核*/,
        onOk: () => {
          this.setState({ hasConfirm: false });
        },
        onCancel: () => {
          this.setState({ hasConfirm: false });
          this.data = [];
          this.connector.close();
          this.handleClickSwitch();
        }
      })
    }
    expense.body = expense.command === 'MESSAGE' ? JSON.parse(expense.body) : '';
    if (!expense.body || !expense.body.type || !expense.body.content) return;
    if (expense.command !== 'MESSAGE') return;
    let content = expense.body.content.split(':');
    let { entityList } = this.state;
    if (expense.body.type === 'AUTH_SUCCESS'){
      this.setState({ connectStatus: true });
    } else if (expense.body.type === 'AUDIT_PASS'){
      let {entityType, businessCode} = this.handleFormDetail(content);
      entityList.unshift({
        type: expense.body.type,
        entityType,
        entityOID: content[2] || '',
        businessCode,
        name: content[4] || '',
        pass: true
      });
      this.setState({ entityList }, () => {
        message.success(`${entityList[0].name}${messages('expense-14.key250')/*的报销单已通过*/}`)
      })
    } else if (expense.body.type === 'AUDIT_REJECT'){
      let {entityType, businessCode} = this.handleFormDetail(content);
      let rejectEntity = {
        type: expense.body.type,
        entityType,
        entityOID: content[2] || '',
        businessCode,
        entityCode: content[3] || '',
        name: content[4] || '',
        pass: false
      };
      this.setState({ rejectEntity })
    }
  };

  handleReject = (e) => {
    e.preventDefault();
    let {attachmentOIDs} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let { rejectEntity, entityList } = this.state;
        let params = {
          approvalTxt: values.approvalTxt,
          entities: [{
            entityOID: +rejectEntity.entityType === 5001 ? rejectEntity.entityCode : rejectEntity.entityOID,
            entityType: rejectEntity.entityType,
            attachmentOIDs
          }]
        };
        this.setState({ loading: true });
        financeAuditService.rejectAudit(params).then(res => {
          let formInfo = +res.data.entityType === 5001 ? messages('expense-14.key248')/*发票袋*/ :
            messages('expense-14.key247')/*单据*/;
          formInfo = res.data.entityCode ? `${formInfo} ${res.data.entityCode}` : '';
          this.setState({ loading: false });
          if (res.data.success) {
            message.success(`${formInfo} ${res.data.msg}`);
            entityList.unshift(JSON.parse(JSON.stringify(rejectEntity)));
            this.setState({ rejectEntity: {}, entityList, attachmentOIDs: []});
          } else {
            message.error(`${formInfo} ${res.data.msg}`)
          }
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response);
        })
      }
    })
  };

  handleClickCancel = () => {
    this.setState({ rejectEntity: {}, attachmentOIDs: []})
  };
  handleImageUpload = attachments => {
    this.setState({attachmentOIDs: attachments.map(a => a.attachmentOID)});
  };
  render(){
    const { entityList, rejectEntity, loading} = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="scan-audit background-transparent">
        <div style={{position: 'absolute', width: 'calc(100% - 57px)', minHeight: 'calc(100% - 80px)'}}>
          <WaterMark />
        </div>
        <Button type="primary" icon="layout" onClick={this.handleClickSwitch}>{messages('expense-14.key251')/*普通审核*/}</Button>
        <div className="reject-audit">
          {rejectEntity.businessCode ? (
            <div className="reject-audit-area">
              <div className="reject-audit-code">{rejectEntity.businessCode}</div>
              <div className="reject-audit-name">{rejectEntity.name}</div>
              <Form onSubmit={this.handleReject}>
                <FormItem style={{margin: '16px 0'}}>
                  {getFieldDecorator('approvalTxt', {
                    rules: [{
                      required: true,
                      message: messages('expense-14.key252')/*请输入驳回意见*/,
                    }, {
                      max: 500,
                      message: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
                    }]
                  })(
                    <QuickReply
                      handleImageUpload={this.handleImageUpload}
                      params={{needHonest: false, withAttachments: true, audit: true}}
                    >
                      <TextArea
                        placeholder={messages('expense-14.key253')/*请填写驳回理由*/}
                        style={{
                          minHeight: 136,
                          height: 32,
                          resize: 'none',
                          marginBottom: 10,
                          marginLeft: window.ISIE9 ? 20 : 0
                        }}
                      />
                    </QuickReply>
                  )}
                </FormItem>
                <Button type="primary" loading={loading} htmlType="submit">{messages('common.reject')/*驳回*/}</Button>
                <Button style={{marginLeft: 8}} onClick={this.handleClickCancel}>{messages('common.cancel')/*取消*/}</Button>
              </Form>
            </div>
          ) : (
            <div className="scan-alert">
              <img src={ScanAuditImg}/>
              <h3>{messages('expense-14.key254')/*请打开汇联易app，扫描单据/发票袋上的二维码*/}</h3>
            </div>
          )}
        </div>
        <div className="pass-audit">
          <h4 className="pass-audit-title">
            {messages('expense-14.key255')/*审核结果(在这里统一显示扫码*/}
            <Tag color="geekblue" style={{marginLeft: 8}}>{messages('common.pass')/*通过*/}</Tag>
            {messages('expense-14.key256')/*和在此页面*/}
            <Tag color="magenta" style={{marginLeft: 8}}>{messages('common.reject')/*驳回*/}</Tag>
            {messages('expense-14.key257')/*的单据）*/}
          </h4>
          <div className="pass-audit-result">
            {entityList.map(entity =>
              <Tag color={entity.pass ? 'geekblue' : 'magenta'} key={entity.entityOID}>{entity.businessCode}</Tag>
            )}
          </div>
        </div>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    authToken: state.main.authToken
  }
}

ScanAudit.contextTypes = {
  router: React.PropTypes.object
};

const WrappedScanAudit = Form.create()(ScanAudit);

export default connect(mapStateToProps)(WrappedScanAudit);
